package com.microframework.boot.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.microframework.base.core.exception.NotFindException;
import com.microframework.base.web.page.PageQuery;
import com.microframework.base.web.resp.R;
import com.microframework.boot.system.model.domain.Menu;
import com.microframework.boot.system.model.domain.Role;
import com.microframework.boot.system.model.domain.RoleMenu;
import com.microframework.boot.system.model.domain.User;
import com.microframework.boot.system.model.domain.UserRole;
import com.microframework.boot.system.service.IOrgService;
import com.microframework.boot.system.service.IUserService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
	
    @Autowired
    private IOrgService orgService;

	@Override
	public Page<User> pages(PageQuery<User> pageQuery) {
		try {
			StringBuilder sqlBuilder = new StringBuilder("FROM " + User.TABLE_NAME + " WHERE 1=1");
			List<Object> params = new ArrayList<>();

			User query = pageQuery.getQuery();
			if (query != null) {
				// 构建查询条件
				if (StringUtils.hasText(query.getUsername())) {
					sqlBuilder.append(" AND username LIKE ?");
					params.add("%" + query.getUsername() + "%");
				}

				if (StringUtils.hasText(query.getCnName())) {
					sqlBuilder.append(" AND cn_name LIKE ?");
					params.add("%" + query.getCnName() + "%");
				}
				
				if (StringUtils.hasText(query.getEnName())) {
					sqlBuilder.append(" AND en_name LIKE ?");
					params.add("%" + query.getEnName() + "%");
				}
				
				if (StringUtils.hasText(query.getEmail())) {
					sqlBuilder.append(" AND email LIKE ?");
					params.add("%" + query.getEmail() + "%");
				}
				
				if (StringUtils.hasText(query.getPhone())) {
					sqlBuilder.append(" AND phone LIKE ?");
					params.add("%" + query.getPhone() + "%");
				}
				
				if (StringUtils.hasText(query.getOrgId())) {
					sqlBuilder.append(" AND org_id = ?");
					params.add(query.getOrgId());
				}
				
				if (StringUtils.hasText(query.getStatus())) {
					sqlBuilder.append(" AND status = ?");
					params.add(query.getStatus());
				}
				
				if(query.getOrgIds() != null && !query.getOrgIds().isEmpty()) {
				    sqlBuilder.append(" AND org_id IN (");
				    String placeholders = query.getOrgIds().stream()
				        .map(id -> "?")
				        .collect(Collectors.joining(","));
				    sqlBuilder.append(placeholders).append(")");
				    params.addAll(query.getOrgIds());
				}
				
				if (StringUtils.hasText(query.getIsDel())) {
					sqlBuilder.append(" AND is_del = ?");
					params.add(query.getIsDel());
				}else {
					sqlBuilder.append(" AND is_del = ?");
					params.add("0");
				}
			}else {
				sqlBuilder.append(" AND is_del = ?");
				params.add("0");
			}

			// 设置排序
			String orderBy = StringUtils.hasText(pageQuery.getOrderBy()) ? pageQuery.getOrderBy() : "modify_time";
			String orderDirection = StringUtils.hasText(pageQuery.getOrderDirection()) ? pageQuery.getOrderDirection()
					: "desc";
			sqlBuilder.append(" ORDER BY " + orderBy + " " + orderDirection);
			String select="select id,org_id,username,cn_name,en_name,email,phone,status,create_time,modify_time";
			
//			
//			
//			List<String> fields =SqlFieldFetcher.getQueryFields(select+sqlBuilder.toString(),  params.toArray());
//			
//	        System.out.println("查询包含字段:");
//	        fields.forEach(System.out::println);
	        
			Page<User> page=User.dao.paginate(pageQuery.getPageNumber(), pageQuery.getPageSize(), select,sqlBuilder.toString(), params.toArray());
			
			for(User user:page.getList()) {
				if(!StrKit.isBlank(user.getOrgId())) {
					user.setOrg(orgService.findById(user.getOrgId()));
				}
			}
			return page;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询用户列表异常{}", e.getMessage());
			return new Page<User>(new ArrayList<>(), 1, 10, 0, 0);
		}
	}

	
	@Override
	public R<User> queryUserLoginInfo(String id) {
	    User user = User.dao.findById(id);
	    if (user == null) {
	        throw new NotFindException("未查询到用户ID为" + id + "的用户信息");
	    }

	    // 获取用户角色信息
	    List<Role> roles = getUserRoles(user.getId());
	    if (roles != null && !roles.isEmpty()) {
	        setUserRolesAndPermissions(user, roles, id);
	    }
	    
	    // 清除敏感信息
	    user.setPassword("");
	    return R.ok(user);
	}

	private List<Role> getUserRoles(String userId) {
	    String sql = "SELECT code FROM " + Role.TABLE_NAME + 
	                 " WHERE id IN (SELECT role_id FROM " + UserRole.TABLE_NAME + 
	                 " WHERE user_id = ?)";
	    return Role.dao.find(sql, userId);
	}

	private void setUserRolesAndPermissions(User user, List<Role> roles, String userId) {
	    // 使用Stream API处理角色集合
	    String[] userRoles = roles.stream()
	                             .map(Role::getCode)
	                             .toArray(String[]::new);
	    user.setRoles(userRoles);

	    // 获取用户权限
	    List<Menu> menus = getUserPermissions(userId);
	    if (menus != null && !menus.isEmpty()) {
	        List<String> userPerms = menus.stream()
	                                     .map(Menu::getPerm)
	                                     .collect(Collectors.toList());
	        user.setPerms(userPerms);
	    }
	}

	private List<Menu> getUserPermissions(String userId) {
	    String sql = "SELECT * FROM " + Menu.TABLE_NAME + 
	                " WHERE type = 'btn' AND id IN (" +
	                "SELECT menu_id FROM " + RoleMenu.TABLE_NAME + 
	                " WHERE role_id IN (" +
	                "SELECT role_id FROM " + UserRole.TABLE_NAME + 
	                " WHERE user_id = ?)) ORDER BY sort ASC";
	    return Menu.dao.find(sql, userId);
	}


}
